package com.hdphone.zljutils.impl;

import android.os.Environment;

import androidx.annotation.NonNull;

import com.hdphone.zljutils.ZljUtils;
import com.hdphone.zljutils.inter.IRemoteLogUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @date: 2021/6/3
 * @email： yzandlj@163.com
 * @author： yangzhi
 * @describe:
 */
public class RemoteLogUtilImpl implements IRemoteLogUtil {

    private static final ExecutorService executorService;
    private static final String mFilePath;
    private static final StringBuffer mSb;
    private static volatile int mWriteCount = 0;

    static {
        executorService = Executors.newSingleThreadExecutor();
        mSb = new StringBuffer();
        mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "check_result_" + System.currentTimeMillis() + ".txt";
    }

    @Override
    public void log(@NonNull String s) {
        mSb.append(ZljUtils.DATE().date2String(new Date())).append(" :  ").append(s).append("\n\n");
        if (mWriteCount > 0) {
            write2File();
        }
    }

    @Override
    public void write2File() {
        executorService.execute(() -> {
            synchronized (RemoteLogUtilImpl.class) {
                try {
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(mFilePath, true));
                    bufferedOutputStream.write(mSb.toString().getBytes());
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();

                    mSb.delete(0, mSb.length());

                    mWriteCount++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
